import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from WindPy import w
from datetime import datetime


def get_batch_wind_data(id_to_name):
    if not w.isconnected():
        w.start() 

    keys = list(id_to_name.keys())
    s = ','.join(keys)

    re = w.edb(
        s, 
        "1999-12-28", "2025-11-30"
        )

    df = pd.DataFrame(
        re.Data,
        index=re.Codes,
        columns=re.Times,
    ).T
    df.columns = [id_to_name[k] for k in keys]
    return df

def plot_last_two_rows(df):
    last_two = df.tail(3)
    fig = px.bar(last_two.T, barmode='group')
    fig.update_layout(
        title='最后两行数据对比',
        xaxis_title='日期',
        yaxis_title='数值',
        barmode='group',
        showlegend=True
    )
    fig.data = sorted(fig.data, key=lambda x: x.x[0])
    return fig

def get_today_date():
    return datetime.now().strftime('%Y-%m-%d')


def update_data():
    meta = pd.read_excel("meta/meta_for_monthly.xlsx", index_col=0)

    for theme, se in meta.items():
        se = se.dropna()
        dic = dict(zip(se.values, se.index))
        df = get_batch_wind_data(dic)
        df = df[-36:]
        theme_path = f"cache\{theme}_{get_today_date()}.xlsx"
        df.to_excel(theme_path)
        print('Done!', theme_path)

if __name__ == '__main__':
    update_data()


